﻿@model ArticleModel
@section style {
    <style>
        .article-load-content .file-select-wrapper { float: none; }
    </style>
}
<div id="article" class="page" v-cloak>
    @if (!Model.IsArticle)
    {
        <Tabs ref="tabs" v-model="currentTab" @@on-tab-remove="tabRemove">
            <TabPane label="@Model.Title">
                @if (ViewData["DataGrid"] != null)
                {
                    @Html.Partial($"{ViewData["DataGrid"]}")
                }
                else
                {
                    <datagrid ref="grid" :columns="gridColumns" :edit="editSetting" :url="'@Model.DataUrl'" :params.once="{menuId:@Model.MenuId,sortId:@Model.SortId,status:0}" v-on:query="beforeQuery" v-on:new="newArticle">
                        @if (Model.ShowAudit)
                        {
                            <Dropdown slot="left_buttons" @@on-click="audit" title="审核">
                                <Dropdown-menu>
                                    <Dropdown-item value="3"><a>通过并发布</a></Dropdown-item>
                                    <Dropdown-item value="2"><a>拒绝发布</a></Dropdown-item>
                                </Dropdown-menu>
                            </Dropdown>
                            <div slot="other_query" class="tb-item">
                                <select name="status" id="article_audit_status" style="width:100px">
                                    <option value="" selected>审核状态</option>
                                    @foreach (var item in Model.AuditStatus)
                                    {
                                        <option value="@item.id">@item.text</option>
                                    }
                                </select>
                            </div>
                        }
                        @if (ViewData["DataQuery"] != null)
                        {
                            @Html.Partial($"{ViewData["DataQuery"]}")
                        }
                    </datagrid>
                }
            </TabPane>
            <TabPane :label="editTitle" closable :destroyable="false" v-model="showTab">
                @Html.Partial("ArticleForm")
            </TabPane>
        </Tabs>
    }
    else
    {
        @Html.Partial("ArticleForm")
    }
</div>
@section script{
    <script>var _columns = null; var __mixins = null;</script>
    @Html.Partial($"{ViewData["ArticleListView"]}")
    @Html.GetEditorScripts()
    <script>
        var _isArticle = @Model.IsArticle.ToString().ToLower();
        var article_vm,  article_editor_cont;
        article_vm = new Vue({
            el: '#article',
            mixins: __mixins,
            data: {
                article_load_type: '',
                videos:[],
                submitting: false,
                loading: false,
                showTab:false,
                currentTab: 0,
                editSetting: { showNew:@Model.ShowNew.ToString().ToLower(),delUrl: '@Model.DelUrl' },
                videoUrl: '',
                videoType: '1',
                editTitle: null,
                gridData: [],
                gridColumns: _columns
            },
            computed: {
                articleLoadPlaceholder: function () {
                    if (this.article_load_type === '1')
                        return '请输入微信文章地址...';
                    if (this.article_load_type === '2')
                        return '请输入网页地址...';
                    return '';
                }
            },
            watch: {
                editTitle(val) {
                    this.showTab = val != null;
                }
            },
            methods: {
                handleEditorChange: function () {
                    setTimeout(this.checkScroll, 150);
                },
                preview: function () {
                    var $form = $('#article_form_preview');
                    $form.find('input[name="Title"]').val($('#Title').val());
                    if (document.getElementById('#Intro'))
                        $form.find('input[name="Intro"]').val(this.$refs.intro.editorCont);
                    $form.find('input[name="Content"]').val(this.$refs.content.editorCont);
                    $form.submit();
                },
                handleLoadArticle: function () {
                    var self = this;
                    var url = this.$refs.article_load_url.value;
                    if (!url) {
                        this.$Message.warning(this.articleLoadPlaceholder);
                        return;
                    }
                    self.loading = true;
                    $.post('@Model.LoadArticleUrl', { type: this.article_load_type === '1' ? 'weixin' : 'web', url: url }, function (result) {
                        if (result.succ === false) {
                            self.$Message.error(result.data);
                        } else {
                            var article = result.data;
                            if (article.Title) {
                                if (self.$refs.title)
                                    self.$refs.title.setValue(article.Title);
                                else
                                    $('#article_title').val(article.Title);
                            }
                            if (article.Author) {
                                $('#article_author').val(article.Author);
                                if (!article.Source)
                                    $('#article_source').val(article.Author);
                            }
                            if (article.Source){
                                $('#article_source').val(article.Source);
                            }
                            if (article.Summary)
                                if (self.$refs.intro)
                                    self.$refs.intro.setValue(article.Summary);
                            if (article.Content)
                                self.$refs.content.setValue(article.Content);
                        }
                    }).always(function () {
                        self.loading = false;
                    });;
                },
                handleRemoveVideo: function (file) {
                    this.$refs.video.handleRemove(file);
                },
                tabRemove: function () {
                    this.editTitle = null;
                },
                resetForm: function () {
                    if (_isArticle) {
                        this.currentTab = 1;
                        this.$refs.content.reset();
                    } else {
                        this.$refs.form.reset();
                    }
                },
                newArticle: function () {
                    this.resetForm();
                    this.videoUrl = '';
                    this.setEdit('新建@{@Html.Raw(Model.MenuName)}');
                },
                setEdit: function (title) {
                    this.editTitle = title;
                    this.currentTab = title === null ? 0 : 1;
                },
                setOrder: function (id, order, type) {
                    $.post('@Model.OrderUrl', { id: id, order: order, type: type }, function (result) {
                        if (result.succ) {
                            article_vm.$refs.grid.reload();
                        } else {
                            alert(result.data);
                        }
                    });
                },
                checkScroll: function () {
                    var formPadding = 20;
                    var formH = $(window).height() - this.$form.offset().top - 10 - formPadding;
                    if (!_isArticle)
                        this.$form.css({ 'height': formH});
                    console.log("checkScroll:", this.$form[0].scrollHeight, formH);
                    //var $edui = $('#edui1');

                    //var $editorCont = $('#edui1_iframeholder');
                    var $submitBar = $('#article_bar');
                    if (this.$form[0].scrollHeight > formH) {
                        this.$form.css({ 'padding': '10px 8px 100px 8px' });
                        if (!$submitBar.hasClass('fix-submit')) {
                            var etTop = this.$Utils.getElementTop(this.$editorToolbar[0], this.$form[0]);
                            this.$editorToolbar.data('top', etTop);
                            $submitBar.addClass('fix-submit');
                        }
                    }
                    else {
                        this.$form.css({ 'padding': '10px 8px' });
                        $submitBar.removeClass('fix-submit');
                    }
                },
                editArticle: function (id, lang) {
                    var self = this;
                    this.resetForm();
                    $.post('@Model.InfoUrl', { id: id, mid:@Model.MenuId, sortId:@Model.SortId, lang: lang }, function (data) {
                        if (data) {
                            if (data.Video)
                                self.videoType = data.Video.indexOf('http') === 0 ? '1' : '2';
                            setTimeout(function () {
                                self.$refs.form.fill(data);
                            }, 200);

                            //$('#article_form').fill(data);
                            self.setEdit('编辑');
                        }
                    });
                },
                delArticle: function (id) {
                    if (confirm("确定删除？")) {
                        $.post('@Model.DelUrl', { menuId:@Model.MenuId, ids: id }, function (result) {
                            if (result.succ) {
                                article_vm.$refs.grid.reload();
                            } else {
                                alert(result.data);
                            }
                        });
                    }
                },
                audit: function (type) {
                    var ids = article_vm.$refs.grid.getIds();
                    if (!ids || !ids.length) {
                        alert("请选择要审核的记录！");
                        return false;
                    }
                    if (confirm("确认对选中的记录做【" + (type == 3 ? "通过" : "拒绝") + "】操作？")) {
                        $.post('@{@Model.AuditUrl}', { menuId: @Model.MenuId, ids: ids, type: type }, function (result) {
                            if (result.succ) {
                                article_vm.$refs.grid.reload();
                            } else {
                                alert(result.data);
                            }
                        });
                    }
                },
                beforeQuery: function (queryParams) {
                    queryParams.status = $('#article_audit_status').val();
                    if (queryParams.status == "") queryParams.status = "0";
                },
                editorReady: function (editor) {
                    if (_isArticle) {
                        this.editArticle('@Model.ArticleId');
                    }else {
                        setTimeout(this.resetForm(), 800);
                    }
                    this.$editorToolbar = $('#edui1_toolbarbox');
                    this.$editorCont = $('#edui1_iframeholder');
                    var self = this;
                    editor.addListener("beforefullscreenchange", function (e, enabled) {
                        if (enabled) {
                            self.$editorToolbar.removeClass('editor-tb-fixed');
                        }
                    });
                    editor.addListener("fullscreenchanged", function (e, fullScreen) {
                        if (fullScreen) {
                            $('#article').addClass('fullscreen');
                            var $edui = $('#edui1');
                            var left = parseInt($edui.css('left').replace(/[^-0-9]/ig, ""));
                            var top = parseInt($edui.css('top').replace(/[^-0-9]/ig, ""));
                            $edui.css({ 'left':(left + 25)+'px', 'top': (top + 10)+'px','z-index':9999 });
                        }
                        else {
                            $('#article').removeClass('fullscreen');
                            setTimeout(self.checkScroll, 50);
                        }
                    });
                },
                submitProgress: function (e) {
                    console.log("submit progress:", e.percent);
                },
                submitSuccess: function (data) {
                    this.setEdit(null);
                    if (this.$refs.grid)
                        this.$refs.grid.reload();
                    this.$Message.success("发布成功");
                },
                checkEditorToolbar: function () {
                    var self = this;
                    var form = this.$form[0];
                    var toolbarTop = this.$editorToolbar.data('top');
                    if (form.scrollTop > toolbarTop) {
                        if (!self.$editorToolbar.hasClass('editor-tb-fixed')) {
                            self.$editorToolbar.addClass('editor-tb-fixed').css({ 'width': $('#edui1').width() });
                            self.$editorCont.css({ 'margin-top': self.$editorToolbar.height() });
                        }
                    } else {
                        if (self.$editorToolbar.hasClass('editor-tb-fixed')) {
                            self.$editorToolbar.removeClass('editor-tb-fixed').removeAttr('style');
                            self.$editorCont.css({ 'margin-top': 0 });
                        }
                    }
                }
            },
            mounted: function () {
                var self = this;
                this.$form = $(this.$refs.form.$el).on('scroll', function () {
                    self.checkEditorToolbar();
                });;
                this.$form.form('select');
                $(window).on('resize', this.checkScroll);
            }
        });
    </script>
    @if (Model.IsArticle)
    {
        <script>
            $('#article_Lang').change(function () {
                var lang = $(this).val();
                article_vm.editArticle(0, lang);
            });
        </script>
    }
}